package com.heima.behavior.service.impl;

import com.heima.behavior.dtos.ArticleBehaviorDto;
import com.heima.behavior.service.ApBehaviorServcie;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.pojos.ApUser;
import com.heima.utils.thread.AppThreadLocalUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class ApBehaviorServcieImpl implements ApBehaviorServcie {

    @Autowired
    private StringRedisTemplate redisTemplate;
    /**
     * 加载文章和行为关系
     *
     * @param dto
     * @return
     */
    @Override
    public ResponseResult load(ArticleBehaviorDto dto) {
        //1.参数校验
        if(dto.getArticleId()==null || dto.getAuthorId()==null){
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2.获取登录用户id,
        ApUser apUser = AppThreadLocalUtil.getApUser();
        //如果没有登录，则不能执行以下步骤，游客身份
        if(apUser!=null && apUser.getId()==0){
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }

        //定义默认变量
        Boolean islike=false,isunlike=false,iscollection=false,isfollow=false;
        //3.根据条件从redis去查询
        // 是否关注过，
        String followKey="USER_FOLLOW_"+apUser.getId();
        Boolean followFlag = redisTemplate.opsForHash().hasKey(followKey, dto.getAuthorId().toString());
        if(followFlag){
            isfollow=true;
        }
        // 是否点赞过，
        String likekey="USER_LIKE_"+dto.getArticleId();
        Boolean likeFlag = redisTemplate.opsForHash().hasKey(likekey, apUser.getId().toString());
        if(likeFlag){
            islike=true;
        }
        // 是否不喜欢，
        String unlikeKey="USER_UNLIKE_"+dto.getArticleId();
        Boolean unlikeFlag = redisTemplate.opsForHash().hasKey(unlikeKey, apUser.getId().toString());
        if(unlikeFlag){
            isunlike=true;
        }
        // 是否收藏过
        String collectionkey="USER_COLLECTION_"+dto.getArticleId();
        Boolean collectionFlag = redisTemplate.opsForHash().hasKey(collectionkey, apUser.getId().toString());
        if(collectionFlag){
            iscollection=true;
        }

        //封装数据
        Map resultMap=new HashMap();
        resultMap.put("islike",islike);
        resultMap.put("isunlike",isunlike);
        resultMap.put("isfollow",isfollow);
        resultMap.put("iscollection",iscollection);


        return ResponseResult.okResult(resultMap);
    }
}
